import 'package:dart_serve_study/common/result.dart';
import 'package:dart_serve_study/dart_serve_study.dart';

class RegisterController extends ResourceController {
  RegisterController(this.context, this.authServer);

  final ManagedContext context;
  final AuthServer authServer;

  @Operation.post()
  // ignore: missing_return
  Future<Response> registerUser(@Bind.body() User user) async {
    //过滤掉空值
    if (user.username == null || user.password == null) {
      return Result.errorMsg('用户名密码不能为空哦！');
    }
    user
      ..salt = AuthUtility.generateRandomSalt() //生成一个随机盐
      ..hashedPassword =
          authServer.hashPassword(user.password, user.salt) //使用PBKDF2算法进行加密
      ..createTime = DateTime.now()
      ..updateTime = DateTime.now();
    if ((await (Query<User>(context)
              ..where((x) => x.username).identifiedBy(user.username))
            .fetchOne()) !=
        null) {
      return Result.errorMsg('用户名已存在');
    }
    await Query<User>(context, values: user).insert(); //插入到数据库中
    return Result.successMsg('注册成功');
  }
}